import React, { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Button, Row, Col, Space, Form, Checkbox, Tabs, Input, message, Modal } from 'antd';
import {
  PlusOutlined,
  MailOutlined,
  PhoneOutlined,
  CloseOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { connect, FormattedMessage, useIntl } from 'umi';
import request from '@/utils/request';
import CateComp from '@/components/CategoryComponent';
import ZoneComp from '@/components/ZoneComponent';
import { EmpSelect } from '@/components/FormItemSelect';
import DocHelper from '@/components/DocHelper';
import QuickMenu from '@/components/QuickMenu';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';

const { TabPane } = Tabs;
const { confirm } = Modal;
const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

const apiURL = '/api/services/app/Customers/';

const ViewPage: React.FC<any> = (props) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any>({});
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [dataSource, setDataSource] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const formRef = useRef<any>();
  const intl = useIntl();

  useEffect(() => {
    fetchData();
  }, [pageIndex, pageSize]);

  const onFinish = (values: any) => {
    const Customer = values.Customer;
    Customer.id = data.id;
    request(apiURL + 'UpdateCustomer', {
      method: 'PUT',
      data: Customer,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success(intl.formatMessage({ id: 'pages.saveSuccess' }));
          fetchData();
        } else {
          message.error(response.error.message);
        }
      }
    });
  };

  const fetchData = async (params: any = null) => {
    setLoading(true);
    let items: any = [];
    await request(apiURL + 'GetList', {
      method: 'GET',
      params: {
        skipCount: (pageIndex - 1) * pageSize,
        maxResultCount: pageSize,
        keywords: params?.customerName ? params?.customerName : params?.custNum,
        isActive: params?.isActive == undefined ? -1 : params?.isActive ? 1 : 0,
      },
    }).then((response) => {
      if (response) {
        if (response.success) {
          items = response.result?.items;
          setTotalCount(response.result?.totalCount);
          setDataSource(items);
        } else {
          message.error(response?.error?.message);
        }
      }
      setLoading(false);
    });
    return items;
  };

  const newObj = () => {
    request(apiURL + 'NewCustomer', {
      method: 'POST',
      data: {
        custNum: '0',
        customerName: '0',
      },
    }).then((response) => {
      if (response) {
        if (response.success) {
          if (response.result.success) {
            message.success(intl.formatMessage({ id: 'pages.newCustomerSuccess' }));
            const data = response.result.data;
            setData(data);
            formRef.current.setFieldsValue({ Customer: data });
            fetchData();
          } else {
            message.error(response.result.message);
          }
        } else {
          message.error(response.error.message);
        }
        setLoading(false);
      }
    });
  };

  const delObj = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete.confirm' }),
      onOk() {
        request(apiURL + 'Delete', {
          method: 'DELETE',
          params: { id: data.id },
        }).then((response) => {
          if (response) {
            if (response.success) {
              formRef.current.resetFields();
              fetchData();
            } else {
              message.error(response.error.message);
            }
          }
        });
      },
    });
  };

  const resetForm = () => {
    setData({});
    formRef.current.resetFields();
  };

  const doEdit = (data: any) => {
    setData(data)
    formRef.current.setFieldsValue({ Customer: data });
  };

  const columns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'pages.customerNum' }),
      dataIndex: 'custNum',
      key: 'custNum',
    },
    {
      title: intl.formatMessage({ id: 'pages.customerName' }),
      dataIndex: 'customerName',
      key: 'customerName',
    },
    {
      title: intl.formatMessage({ id: 'pages.status' }),
      dataIndex: 'isActive',
      key: 'isActive',
      valueType: 'select',
      fieldProps: {
        options: [
          {
            label: intl.formatMessage({ id: 'pages.active' }),
            value: true,
          },
          {
            label: intl.formatMessage({ id: 'pages.inactive' }),
            value: false,
          },
        ],
      },
    },
    {
      title: intl.formatMessage({ id: 'pages.action' }),
      hideInSearch: true,
      render: (_: any, record: any) => (
        <Button size="small" type="default" onClick={() => doEdit(record)}>
          <FormattedMessage id="pages.edit" />
        </Button>
      ),
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Row gutter={[16, 16]}>
        <Col xs={24} sm={24} md={24} lg={12} xl={12}>
          <Form {...layout} ref={formRef} onFinish={onFinish}>
            <Card
              title={<FormattedMessage id="menu.saleorder.customer" />}
              extra={
                <Space key="S1">
                  <DocHelper page="xnzpv6" />
                  <QuickMenu
                    path="/saleorder/customer"
                    icon="icon-businessman"
                    title="pages.CustomerManage"
                  />
                  <Button type="primary" icon={<PlusOutlined />} onClick={() => newObj()}>
                    <span>
                      <FormattedMessage id="pages.new" />
                    </span>
                  </Button>
                  <Button type="default" onClick={() => resetForm()}>
                    <span>
                      <FormattedMessage id="pages.reset" />
                    </span>
                  </Button>
                  <Button type="primary" htmlType="submit" disabled={!data?.id}>
                    <span>
                      <FormattedMessage id="pages.save" />
                    </span>
                  </Button>
                  <Button
                    type="primary"
                    danger
                    icon={<CloseOutlined />}
                    onClick={() => delObj()}
                    disabled={!data?.id}
                  >
                    <span>
                      <FormattedMessage id="pages.delete" />
                    </span>
                  </Button>
                </Space>
              }
            >
              <Tabs defaultActiveKey="1">
                <TabPane tab={<FormattedMessage id="pages.detail" />} key="1">
                  <Form.Item
                    label={<FormattedMessage id="pages.customerNum" />}
                    name={['Customer', 'custNum']}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.CustomerNum.required" /> },
                    ]}
                  >
                    <Input style={{ width: 200 }} />
                  </Form.Item>
                  <Form.Item
                    label={<FormattedMessage id="pages.customerName" />}
                    name={['Customer', 'customerName']}
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.CustomerName.required" />,
                      },
                    ]}
                  >
                    <Input />
                  </Form.Item>
                  <EmpSelect
                    showSearch
                    width={200}
                    name={['Customer', 'saler']}
                    label={<FormattedMessage id="pages.saler" />}
                    params={{
                      deptCode: 'SD',
                    }}
                  />
                  <CateComp
                    layout="currency"
                    width={200}
                    cRef={formRef}
                    name={['Customer', 'currency']}
                    label={intl.formatMessage({ id: 'pages.currency' })}
                  />
                  <Form.Item
                    name={['Customer', 'contactor']}
                    label={<FormattedMessage id="pages.contactor" />}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.contactor.required" /> },
                    ]}
                  >
                    <Input style={{ width: 200 }} />
                  </Form.Item>
                  <Form.Item
                    name={['Customer', 'telphone']}
                    label={<FormattedMessage id="pages.telphone" />}
                  >
                    <Input prefix={<PhoneOutlined />} style={{ width: 200 }} />
                  </Form.Item>
                  <Form.Item
                    name={['Customer', 'mobile']}
                    label={<FormattedMessage id="pages.mobile" />}
                  >
                    <Input style={{ width: 200 }} />
                  </Form.Item>
                  <Form.Item
                    name={['Customer', 'email']}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.email.required" /> },
                    ]}
                    label={<FormattedMessage id="pages.email" />}
                  >
                    <Input prefix={<MailOutlined />} style={{ width: 240 }} />
                  </Form.Item>
                  <ZoneComp
                    layout="Zone"
                    width={100}
                    label={<FormattedMessage id="pages.zone" />}
                    name="Customer"
                  />
                  <Form.Item
                    name={['Customer', 'contAddress']}
                    label={<FormattedMessage id="pages.address" />}
                  >
                    <Input.TextArea />
                  </Form.Item>
                  <Form.Item wrapperCol={{ offset: layout.labelCol.span }}>
                    <Input.Group compact>
                      <Form.Item name={['Customer', 'isActive']} valuePropName="checked">
                        <Checkbox>
                          <FormattedMessage id="pages.valid" />
                        </Checkbox>
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                </TabPane>
                <TabPane tab={<FormattedMessage id="pages.others" />} key="2">
                  <Form.Item
                    name={['Customer', 'regAddress']}
                    label={<FormattedMessage id="pages.regAddress" />}
                  >
                    <Input.TextArea />
                  </Form.Item>
                  <Form.Item
                    name={['Customer', 'businessLicense']}
                    label={<FormattedMessage id="pages.businessLicense" />}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    name={['Customer', 'industry']}
                    label={<FormattedMessage id="pages.industry" />}
                  >
                    <Input />
                  </Form.Item>
                </TabPane>
              </Tabs>
            </Card>
          </Form>
        </Col>
        <Col xs={24} sm={24} md={24} lg={12} xl={12}>
          <Card>
            <ProTable
              columns={columns}
              dataSource={dataSource}
              rowKey="id"
              key="id"
              bordered={false}
              request={async (params = {}) => {
                return fetchData(params);
              }}
              defaultSize="small"
              pagination={{
                pageSize,
                total: totalCount,
                onChange: (page, _pageSize) => {
                  setPageIndex(page);
                  setPageSize(_pageSize);
                },
              }}
              onRow={(record) => {
                return {
                  onDoubleClick: () => {
                    setData(record);
                  },
                };
              }}
              search={{
                filterType: 'light',
              }}
            />
          </Card>
        </Col>
      </Row>
    </PageHeaderWrapper>
  );
};

export default ViewPage;
